package com.example.dubbo.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dubbo.api.dto.OrderDTO;
import com.example.dubbo.api.enums.RspStatusEnum;
import com.example.dubbo.api.response.ObjectResponse;
import com.example.dubbo.api.dubbo.AccountService;
import com.example.dubbo.order.dao.OrderTblDao;
import com.example.dubbo.order.entity.OrderTblEntity;
import com.example.dubbo.order.service.OrderTblService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.UUID;

/**
 * @author Liyuhang
 */
@Service("orderTblService")
public class OrderTblServiceImpl extends ServiceImpl<OrderTblDao, OrderTblEntity> implements OrderTblService {

    @DubboReference(version = "1.0.0" )
    private AccountService accountDubboService;

    /**
     * 创建订单
     * @Param:  OrderDTO  订单对象
     * @Return:  OrderDTO  订单对象
     */
    @Override
    public ObjectResponse<OrderDTO> createOrder(OrderDTO orderDTO) {
        ObjectResponse<OrderDTO> response = new ObjectResponse<>();
        //扣减用户账户
        ObjectResponse objectResponse = accountDubboService.debit(orderDTO.getUserId(),orderDTO.getOrderAmount().intValue());
        //生成订单号
        orderDTO.setOrderNo(UUID.randomUUID().toString().replace("-",""));
        //生成订单
        OrderTblEntity tOrder = new OrderTblEntity();
        BeanUtils.copyProperties(orderDTO,tOrder);
        tOrder.setCount(orderDTO.getOrderCount());
        tOrder.setMoney(orderDTO.getOrderAmount().intValue());
        try {
            baseMapper.insert(tOrder);
        } catch (Exception e) {
            response.setStatus(RspStatusEnum.FAIL.getCode());
            response.setMessage(RspStatusEnum.FAIL.getMessage());
            return response;
        }
        if (objectResponse.getStatus() != 200) {
            response.setStatus(RspStatusEnum.FAIL.getCode());
            response.setMessage(RspStatusEnum.FAIL.getMessage());
            return response;
        }
        response.setStatus(RspStatusEnum.SUCCESS.getCode());
        response.setMessage(RspStatusEnum.SUCCESS.getMessage());
        return response;
    }

}